package com.dhl.fin.api.service;

import com.dhl.fin.api.common.dto.QueryDto;
import com.dhl.fin.api.common.service.CommonService;
import com.dhl.fin.api.common.util.DateUtil;
import com.dhl.fin.api.common.util.WebUtil;
import com.dhl.fin.api.domain.PaymentRecord;
import com.dhl.fin.api.dto.RisePayOrderReqDTO;
import com.dhl.fin.api.enums.PayStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author CuiJianbo
 * @since 2025/3/16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PaymentRecordService extends CommonService<PaymentRecord> {


    @Autowired
    private WeixinPayService weixinPayService;

    @Override
    public void beforeSave(PaymentRecord domain) {
        domain.setWxAccountCode(WebUtil.getLoginUser().getUuid());
    }


    public void savePaymentRecord(RisePayOrderReqDTO risePayOrderReqDTO, String outTradeNo) throws Exception {
        PaymentRecord paymentRecord = new PaymentRecord();
        paymentRecord.setWxAccountCode(WebUtil.getLoginUser().getUuid());
        paymentRecord.setTotalMoney(risePayOrderReqDTO.getTotalMoney());
        paymentRecord.setYear(DateUtil.getCurrentYear());
        paymentRecord.setMonth(DateUtil.getCurrentMonth());
        paymentRecord.setYears(risePayOrderReqDTO.getYears());
        paymentRecord.setYearPrice(risePayOrderReqDTO.getYearPrice());
        paymentRecord.setStatus(PayStatusEnum.WAITING_PAY.getCode());
        paymentRecord.setFamilyIdList(risePayOrderReqDTO.getFamilyIdList());
        paymentRecord.setBankCardIdList(risePayOrderReqDTO.getBankCardIdList());
        paymentRecord.setOutTradeNo(outTradeNo);

        save(paymentRecord);
    }

    public void updatePayStatus(String status, String outTradeNo) throws Exception {

        String transactionId = weixinPayService.queryStatusByOrderNumber(outTradeNo).getTransactionId();

        PaymentRecord paymentRecord = new PaymentRecord();
        paymentRecord.setTransactionNo(transactionId);
        paymentRecord.setStatus(status);

        updateBySelective(paymentRecord, QueryDto.builder()
                .available()
                .addWhere("out_trade_no='" + outTradeNo + "'")
                .build());
    }

    /**
     * 退款成功后更新支付状态
     */
    public void changePayOrderStatusToRefund(String outTradeNo, String transaction) throws Exception {
        PaymentRecord paymentRecord = new PaymentRecord();
        paymentRecord.setStatus(PayStatusEnum.REFUND.getCode());

        updateBySelective(paymentRecord,
                QueryDto.builder()
                        .available()
                        .addWhere("transaction_no='" + transaction + "'")
                        .addWhere("out_trade_no='" + outTradeNo + "'")
                        .build());
    }


}
